package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @PostMapping
    public Result upload(MultipartFile image) throws IOException {
        String realFileName = image.getOriginalFilename();
        //1.jpg  2.png
        //获取文件名得后缀
        String suffix = realFileName.substring(realFileName.lastIndexOf("."));
        //随机生成文件名防止覆盖
        String randomStr = UUID.randomUUID().toString().replace("-", "");
        //按日期生成文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String dir = simpleDateFormat.format(new Date());
        String fileName = dir+"/"+randomStr+suffix;
        String url = aliyunOssUtil.upload(fileName, image.getInputStream());
        return Result.success(url);
    }
}
